package com.okhttpdemo.http;

import android.content.Context;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.okhttpdemo.bean.MyResponse;
import com.okhttpdemo.utils.Logger;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by 黄海 on 2017/2/28.
 */

public abstract class BaseCallBack<T> implements ICallBase<T> {
    private static final java.lang.String TAG = "BaseCallBack";

    @Override
    public void onStart() {

    }

    @Override
    public void onResponse(Call call, MyResponse<T> response) throws IOException {

    }

    @Override
    public void onFailure(Context context, Call call, Exception t) {
        Logger.e(TAG, "onFailure() called with: call = [" + call + "], t = [" + t + "]");
        if (t instanceof UnknownHostException || t instanceof SocketTimeoutException || t instanceof ConnectException) {
            Toast.makeText(context, "网络错误，请稍候重试", Toast.LENGTH_SHORT).show();
        } else if (t instanceof ParseResponseException) {
            Toast.makeText(context, "数据解析失败，请稍候重试", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(context, "未知错误，请稍候重试", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onProgress(long sended, long totalLength) {

    }

    @Override
    public void onComplete() {

    }

    @Override
    public T parseResponse(Response response) throws ParseResponseException, IOException {
        Type type = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        Logger.i("ParameterizedType=" + type);
        String stringBody = response.body().string();
        Logger.e("请求 = [" + response.request().url().toString() + "], 响应 = [" + stringBody + "]");
        if (type == String.class) {
            return (T) stringBody;
        } else {
            try {
                return JSON.parseObject(stringBody, type);
            } catch (Exception e) {
                throw new ParseResponseException("数据解析失败", e);
            }
        }
    }
}
